// socket/chatHandler.js
const Chat = require('../models/Chat');
const { v4: uuidv4 } = require('uuid');
const { sendToRoom } = require('../utils/socketUtils');
const User = require('../models/User');

function getRoomId(userA, userB) {
  return [userA, userB].sort().join('-');
}

function registerChatEvents(io, socket) {
  socket.on('joinPrivateChat', ({ userId, partnerId }) => {
    const roomId = getRoomId(userId, partnerId);
    socket.join(roomId);
    socket.currentRoomId = roomId; // 记录当前房间ID
    console.log(roomId, "建立私聊");
  });

  socket.on('leavePrivateChat', ({ userId, partnerId }) => {
    const roomId = getRoomId(userId, partnerId);
    // socket.leave(roomId);
    if (socket.currentRoomId === roomId) delete socket.currentRoomId;
    console.log(roomId, "断开私聊", (userId));
  });

  socket.on('sendMessage', async ({ senderId, receiverId, content, mode }) => {
    try {
      const chat = new Chat({ senderId, receiverId, content, mode, messageId: uuidv4() });
      await chat.save();

      const sender = await User.findOne({ userId: senderId });
      const receiver = await User.findOne({ userId: receiverId });

      const roomId = getRoomId(senderId, receiverId);
      io.to(receiverId).emit('newMessageNotice', { from: senderId });
      console.log(sender.nickname, "对", receiver.nickname, "说:", content);
      sendToRoom(io, roomId, 'newMessageNotice', { from: null });
    } catch (err) {
      console.error('sendMessage 出错:', err.message);
    }
  });
}

module.exports = { registerChatEvents };
